package com.mew.chess.core.game.lh.game.task;


import com.mew.chess.core.common.handler.ChessPushMessageUtil;
import com.mew.chess.core.common.handler.GameCommonService;
import com.mew.chess.core.game.lh.game.LhGameManager;
import com.mew.chess.core.game.lh.game.LhRoomManager;
import com.mew.chess.core.game.lh.game.common.LhConstantValue;
import com.mew.chess.core.game.lh.game.common.LhLinkType;
import com.mew.chess.core.game.lh.game.message.LhPushCMDMapType;
import com.mew.chess.core.game.lh.game.message.LhPushStartGameMessage;
import com.mew.chess.core.game.lh.game.message.LhUserMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 * 1, 如果X把不押注 则请出房间
 * 2, 如果服务器已关闭，则清楚房间；
 * 3，开始清数据，
 */
@Component
@Slf4j
public class LhStartBetTask {

    @Autowired
    private GameCommonService gameCommonService;


    public boolean startBet(int roomId){

        LhRoomManager roomManager = LhGameManager.getInstance().getController(roomId);
        roomManager.getOnlineUser().forEach((k, session) -> {
            if (null == session || session.isWeakClose()){
                roomManager.clearOnlineUser(k);
            }
        });

        gameCommonService.checkTMSOnline(roomManager.getOnlineUser().values().stream().collect(Collectors.toList()),  LhGameManager.getInstance().getGameId(), roomId);

        if (roomManager.getOnlineUser().isEmpty()){
            log.info("Lh roomId {} not real user is stop ", roomId);
            roomManager.stopGame();
            return false;
        }

        List<LhUserMessage> bigRList = roomManager.getBigRList();
        //------start game-----
        startGameLinkType(roomManager);

        sendStartMsg(roomManager,bigRList);

        return true;
    }

    public void startGameLinkType(LhRoomManager roomManager){
        roomManager.setRuleTime(LhConstantValue.START_TIME);
        roomManager.setLinkType(LhLinkType.Start.code());
        roomManager.setStartTime(System.currentTimeMillis());
        roomManager.freshINO();
    }

    private void sendStartMsg(LhRoomManager roomManager,List<LhUserMessage> bigRList){
        LhPushStartGameMessage startGameMessage = LhPushStartGameMessage.builder()
                .online(roomManager.getPlayerList().size())
                .remainTime(LhConstantValue.START_TIME)
                .bigRList(bigRList)
                .ino(roomManager.getIno())
                .build();
        roomManager.getOnlineUser().forEach((k, session) -> {
            ChessPushMessageUtil.pushMessage(session,LhPushCMDMapType.StartGameMessage.code(),startGameMessage);

        });
    }

}
